<template>
  <el-dialog :title="'修改入住类型'" :close-on-click-modal="false" :visible.sync="visible" :append-to-body="true">
    <el-form v-loading="loading"  :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="房间总价" prop="name">
        <el-popover placement="bottom" trigger="hover">
          <!-- 新版-->
          <div class="ant-popover-inner-content">
            <div class="recent_price_ul table_recent_price_ul">
              <table>
                <thead>
                  <tr>
                    <th>
                      <div class="list_box clear_float">
                        <span style="width: 100%;">价格</span>
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>
                      <div class="list_box clear_float">
                        <span v-for="(item, index) in prices.dateList" :key="index">
                          <div>{{dateList[index]}}</div>
                          <div style="margin-bottom: 6px;">
                            <el-input-number size="mini" @change="changeTotalPrice(prices.dateList)"
                              v-model="item[dateList[index]]" :precision="2" :step="100" :min="0"></el-input-number>
        
                          </div>
                        </span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <span slot="reference">
            {{ totlMoney }}
            <i class="el-icon-edit" style="cursor: pointer;"></i>
          </span>
        </el-popover>
      </el-form-item>
      <el-form-item label="入住类型" prop="checkinType">
        <!-- 入住类型（0全天1时租2自用3免费） -->
        <el-select v-model="dataForm.checkinType" @change="checkinTypeChange" placeholder="请选择">
          <el-option label="全天" :value="0"></el-option>
          <el-option label="时租" :value="1"></el-option>
          <el-option label="自用" :value="2"></el-option>
          <el-option label="免费" :value="3"></el-option>
          <el-option label="长包" :value="4"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="时长" prop="days" v-if="dataForm.checkinType == 1">
        <el-select v-model="dataForm.housId" @change="hoursChange" placeholder="请选择">
          <el-option v-for="item in options.housOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remarks">
        <el-input v-model="dataForm.certificatesNumber" placeholder="原因" type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button :disabled="loading" @click="visible = false">{{$t('Common.Cancel')}}</el-button>
      <el-button :disabled="loading" type="primary" @click="changeTypeReq()">{{ $t('Common.Confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import moment from 'moment';
  export default {
    data() {
      return {
        roomPrices: [],
        totlMoney: 0,
        dateList: [],
        visible: false,
        loading: false,
        arrivalsTime: '',
        item: {},
        singleEntity: {
          checkinType: 0,
        },
        options: {
          sellerMenberOp: [],
          housOptions: [],
        },
        prices: {
          dateList: [],
        },
        dataForm: {
          singleId: 0,
          floorRoomId: 0,
          checkinType: 0,
          remarks: '',
          housId: '',
        },
        hoursMoney: true
      };
    },
    watch: {
      prices(newVal) {
        if (newVal.dateList) {
          this.hoursMoney = true
        }
      }
    },
    components: {},
    methods: {
      //计算总金额
      changeTotalPrice(list) {
        this.totlMoney = 0;
        list.forEach((item, index) => {
          this.totlMoney += parseFloat(item[this.dateList[index]]);
        });
      },
      hoursChange(hoursId) {
        this.reqRoomHoursPrice([{
          roomId: this.singleEntity.floorRoomEntity.roomId
        }]);
      },
      checkinTypeChange(val) {
        if (val == 0 || val == 2 || val == 3 || val == 4) {
          this.refreshRoomList();
        }
        if (val == 1) {
          if (!this.dataForm.housId) {
            if (this.options.housOptions.length > 0) {
              this.dataForm.housId = this.options.housOptions[0].id;
            } else {
              this.$message.error('请设置钟点房计费规则');
            }
          }
          this.reqRoomHoursPrice([{
            roomId: this.singleEntity.floorRoomEntity.roomId
          }]);
        }
      },
      //获取钟点房规则
      getroomhours() {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroomhours/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: 1,
            limit: 999
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.options.housOptions = data.page.list;
          } else {
            this.options.housOptions = [];
          }
        });
      },
      reqRoomHoursPrice(arr) {
        this.loading = true
        var idArr = [];
        arr.forEach((item, index) => {
          idArr.push(item.roomId);
        });
        var ids = idArr.join(',');
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomhours/room_hours_money`),
          method: 'get',
          params: this.$http.adornParams({
            startDate: moment(this.singleEntity.peopleEntity.arrivalsTime).format('YYYY-MM-DD'),
            endDate: moment(this.singleEntity.peopleEntity.arrivalsTime)
              .add(1, 'days')
              .format('YYYY-MM-DD'),
            hoursId: this.dataForm.housId,
            roomIds: ids
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log(data);
            data.data.forEach((item, index) => {
              if (item.roomId == this.singleEntity.floorRoomEntity.roomId) {
                this.prices = JSON.parse(JSON.stringify(item))

                this.hoursMoney = this.prices.hoursMoney
                if (!this.hoursMoney) {
                  this.$message.error('此房型未关联此钟点房方案')
                  this.loading = false
                  return
                }
              }
            });
            this.changeTotalPrice(this.prices.dateList)
          } else {
            this.$message.error(data.msg);
          }
          this.loading = false
        });
      },
      refreshRoomList() {
        //改价格
        this.reqRoomPrice([{
          roomId: this.singleEntity.floorRoomEntity.roomId
        }]);
      },
      reqRoomPrice(arr) {
        this.loading = true
        var idArr = [];
        arr.forEach((item, index) => {
          idArr.push(item.roomId);
        });
        var ids = idArr.join(',');

        var params = {}
        if (this.singleEntity.singleCheckinTypeEntity.checkinType == 1) {
          params = {
            startDate: moment(this.singleEntity.peopleEntity.arrivalsTime).format('YYYY-MM-DD'),
            endDate: moment(this.singleEntity.peopleEntity.arrivalsTime).add(1, 'days').format('YYYY-MM-DD'),
            ids: ids
          }
        } else {
          params = {
            startDate: moment(this.singleEntity.peopleEntity.arrivalsTime).format('YYYY-MM-DD'),
            endDate: moment(this.singleEntity.peopleEntity.predissociationTime).format('YYYY-MM-DD'),
            ids: ids
          }
        }

        this.$http({
          url: this.$http.adornUrl(`/hotel/hotelroomprice/list3`),
          method: 'get',
          params: this.$http.adornParams(params)
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            data.data.dataList.forEach((item, index) => {
              if (item.roomId == this.singleEntity.floorRoomEntity.roomId) {
                let _obj = JSON.stringify(item),
                  objClone = JSON.parse(_obj);
                this.prices = objClone;
                console.log(item);
              }
            });
            //会员折扣价
            // if (this.selectMenberFlag) {
            //   var arr = this.prices.dateList;
            //   for (var i = 0; i < this.dataForm.days; i++) {
            //     arr[i][this.dateList[i]] = (parseFloat(arr[i][this.dateList[i]]) * parseFloat(this.selectSellerMenber
            //       .discount)).toFixed(2)
            //   }
            // }
            //免费自用
            if (this.dataForm.checkinType == 2 || this.dataForm.checkinType == 3) {
              var arr = this.prices.dateList;
              for (var i = 0; i < this.prices.dateList.length; i++) {
                arr[i][this.dateList[i]] = 0
              }
            }
            this.changeTotalPrice(this.prices.dateList)
          } else {
            this.$message.error(data.msg);
          }
          this.loading = false
        });
      },
      //加载日期
      getdateList() {
        this.dateList = [];
        //加载日期
        for (var i = 0; i < 99; i++) {
          this.dateList.push(
            moment(this.arrivalsTime)
            .add(i, 'days')
            .format('YYYY-MM-DD')
          );
        }
      },
      getInfo() {
        this.loading = true;
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinsingle/getInfo/${this.dataForm.singleId}`),
          method: 'get',
          params: this.$http.adornParams({
            floorRoomId: this.dataForm.floorRoomId
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.singleEntity = data.singleEntity
            this.dataForm.checkinType = data.singleEntity.singleCheckinTypeEntity.checkinType
            this.dataForm.housId = data.singleEntity.singleCheckinTypeEntity.housId
            this.prices = JSON.parse(data.singleEntity.peopleEntity.sign)
            this.changeTotalPrice(this.prices.dateList)
          } else {
            this.$message.error(data.msg)
          }
          this.loading = false;
        })
      },
      init(singleId, floorRoomId,arrivalsTime) {
        Object.assign(this.$data, this.$options.data())
        this.visible = true;
        this.arrivalsTime = arrivalsTime;
        this.dataForm.singleId = singleId;
        this.dataForm.floorRoomId = floorRoomId;
        this.getdateList();
        this.getInfo();
        this.getroomhours();
      },
      changeTypeReq() {
        if (!this.hoursMoney) {
          this.$message.error('此房型未关联此钟点房方案')
          return
        }

        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelfloorroomcheckinsingle/change_type`),
          method: 'post',
          data: this.$http.adornData({
            ...this.dataForm,
            singleChinkTypeId: this.singleEntity.singleCheckinTypeEntity.id,
            prices: JSON.stringify(this.prices)
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.$nextTick(() => {
              this.$emit('refreClosing');
              this.$emit('refreshDataList')
            });
            this.visible = false
            this.$message({
              message: this.$t('Common.OperationSuccessful'),
              type: 'success',
              duration: 1500,
              onClose: () => {

              }
            });
          } else {
            this.$message.error(data.msg)
          }
        })
      }

    }
  };
</script>


<style lang="scss" scoped>
  .ant-popover-inner-content {
    padding: 12px 16px;
    color: #002140;

    .table_recent_price_ul {
      max-width: 900px;

      table {
        border-collapse: collapse;
        width: 100%;

        thead,
        th,
        tr,
        tt,
        u,
        ul,
          {
          font: inherit;
          font-size: 100%;
          margin: 0;
          padding: 0;
          vertical-align: initial;
          border: 0;
        }


      }

    }

  }

  .recent_price_ul table th>.list_box>span {
    line-height: 36px;
    background: #f0f0f0;
    height: 36px;
  }

  .table_recent_price_ul.table_recent_price_ul table tbody tr td:first-of-type .list_box span {
    height: calc(100% + 1px);
  }

  .recent_price_ul table td>.list_box>span {
    height: 95px;
  }

  .recent_price_ul table td>.list_box>span,
  .recent_price_ul table th>.list_box>span {
    float: left;
    width: 150px;
    text-align: center;
    border: 1px solid rgba(0, 0, 0, .25);
    margin-left: -1px;
    margin-top: -1px;
  }

  .recent_price_ul table td:first-of-type>.list_box span>div:first-of-type,
  .recent_price_ul table td>.list_box>span>div:first-of-type {
    margin-top: 8px;
    margin-bottom: 6px;
  }

  .table_recent_price_ul.table_recent_price_ul td:nth-of-type(2) .list_box {
    max-height: 340px;
    overflow: auto;
  }
</style>
